import Bb from 'backbone';
import ExpenseKmModel from './ExpenseKmModel.js';
import Radio from 'backbone.radio';
import { round } from '../../math.js';

const ExpenseKmCollection = Bb.Collection.extend({
    /*
     * Collection for expenses related to km fees
     */
    model: ExpenseKmModel,
    initialize(){
        this.on('destroyed', this.channelCall);
        this.on('saved', this.channelCall);
    },
    channelCall: function(){
        var channel = Radio.channel('facade');
        channel.trigger('changed:kmline');
    },
    url(){
        return AppOption['context_url'] + '/kmlines';
    },
    total_km: function(category){
      /*
       * Return the total value
       */
      var result = 0;
      this.each(function(model){
        if (category != undefined){
          if (model.get('category') != category){
            return;
          }
        }
        result += model.getKm();
      });
      return result;
    },
    total_tva: function(category){
        return 0;
    },
    total_ht: function(category){
        return this.total(category);
    },
    total: function(category){
      var result = 0;
      this.each(function(model){
        if (category != undefined){
          if (model.get('category') != category){
            return;
          }
        }
        result += round(model.total());
      });
      return result;
    }
});
export default ExpenseKmCollection;
